package com.barry.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;

/**
 * 腾讯云上传下载工具
 * Created by Steve on 2018/10/11 0011.
 */
public class COSUtil {
    private static final Logger logger = LoggerFactory.getLogger(COSUtil.class);

    // 输出地址
    private static String downLoadFile = "";

    private static CloudStorageConfig cloudStorageConfig = new CloudStorageConfig();

    private static COSClient cosClient;
    static {
        // 1 传入获取到的临时密钥 (tmpSecretId, tmpSecretKey, sessionToken)
        String tmpSecretId = "AKIDP2pb9Up77wtb8VCgcS4oR58xvjEUsSlp";
        String tmpSecretKey = "61iFlZGtQnwspy0lWVFn9HMJ3INhc1oN";
        String sessionToken = "COS_TOKEN";
        BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
        // 2 设置 bucket 的区域, COS 地域的简称请参阅 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参阅源码或者常见问题 Java SDK 部分
        Region region = new Region("COS_REGION");
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端
        cosClient = new COSClient(cred, clientConfig);
    }

    /**
     * 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
     *
     * @param file
     * @return
     */
    public static void uploadFile(File file, String fileKey) throws Exception {
        // 指定要上传到 COS 上对象键
        // 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中，对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
        PutObjectRequest putObjectRequest = new PutObjectRequest(cloudStorageConfig.getQcloudBucketName(), fileKey, file);
        cosClient.putObject(putObjectRequest);
        logger.info("{} 上传腾讯云完成", fileKey);
    }

    /**
     * 获取腾讯云下载url
     *
     * @param key 文件名称：201810151649078611545515.pdf
     * @return
     */
    public static String getDownLoadUrl(String key) {
        // 设置URL过期时间为1小时 60*60*1000()
        Date expiration = new Date(new Date().getTime() + 60 * 60 * 1000);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(cloudStorageConfig.getQcloudBucketName(), key);
        // 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(5分钟)
        generatePresignedUrlRequest.setExpiration(expiration);
        String url = cosClient.generatePresignedUrl(generatePresignedUrlRequest).toString();
        logger.info("获取腾讯云签名：{}", url);
        return url;
    }

    /**
     * 下载文件
     *
     * @param fileKey
     */
    public static File downloadFile(String fileKey) {
        // 指定要下载到的本地路径
        File file = new File(downLoadFile + "export/" + fileKey);
        // 指定要下载的文件所在的 bucket 和对象键
        GetObjectRequest getObjectRequest = new GetObjectRequest(cloudStorageConfig.getQcloudBucketName(), fileKey);
        cosClient.getObject(getObjectRequest, file);
        logger.info("{} 腾讯云下载文件完成", fileKey);
        return file;
    }

    /**
     * 下载文件流
     *
     * @param fileKey
     */
    public static COSObjectInputStream downLoadFileStream(String fileKey) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cloudStorageConfig.getQcloudBucketName(), fileKey);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        return cosObject.getObjectContent();
    }
}
